package com.charging.business.handle;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.charging.business.config.MinFeeManager;
import com.charging.business.enums.Issuer;
import com.charging.business.exception.CustomizeException;
import com.charging.business.service.FeeInEtcHandle;
import com.charging.business.service.FeeInMtcHandle;
import com.charging.business.vo.*;
import com.charging.common.utils.DateUtils;
import com.charging.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author JerryLu
 * @date 2024/8/26 11:04
 * @description 入口计费处理
 */
@Component
@Slf4j
public class FeeEnCalcHandle {
    private static final Logger logger = LoggerFactory.getLogger(FeeEnCalcHandle.class);

    private final FeeInEtcHandle etcHandle;
    private final FeeInMtcHandle mtcHandle;
    private final MinFeeManager feeManager;

    @Autowired
    public FeeEnCalcHandle(FeeInEtcHandle etcHandle, FeeInMtcHandle mtcHandle, MinFeeManager feeManager) {
        this.etcHandle = etcHandle;
        this.mtcHandle = mtcHandle;
        this.feeManager = feeManager;
    }

    /**
     * 入口计费包含ETC和CPC
     *
     * @param jsonObject
     * @return com.charging.business.vo.PublicReturn
     * @author JerryLu
     * @date 2024/9/26 11:04
     */
    public BasicResponse handle(JSONObject jsonObject) {
        BasicResponse result = new BasicResponse();
        FeeEnCalcResponse response = new FeeEnCalcResponse();
        BasicRequest basicRequest = JSON.parseObject(jsonObject.toString(), BasicRequest.class);
        FeeEnCalcRequest requestBiz = JSON.parseObject(basicRequest.getBizContent(), FeeEnCalcRequest.class);

        String msg = this.check(basicRequest, requestBiz);
        if (!msg.isEmpty()) {
            response.setCode(-1);
            response.setCodeInfo(msg);
        } else {
            try {
                if (requestBiz.getEnTollStationHex().startsWith(Issuer.Issue610101.getProvinceCode())) {
                    switch (requestBiz.getMediaType()) {
                        // OBU/ETC
                        case 1:
                            logVehicleEntityInfo(requestBiz, "OBU天线");
                            response = this.etcHandle.run(requestBiz, response);
                            break;
                        // MTC/CPC
                        case 2:
                            logVehicleEntityInfo(requestBiz, "CPC刷卡");
                            response = this.mtcHandle.run(requestBiz, response);
                            break;
                        // 纸券
                        case 3:
                            logVehicleEntityInfo(requestBiz, "纸券");
                            response = this.mtcHandle.run(requestBiz, response);
                            break;
                        // 无通行介质
                        case 9:
                            logger.info("车辆：{} 到达出口,无此通行类型", requestBiz.getVehicleId());
                            response.setCode(-1);
                            response.setCodeInfo("无此通行类型");
                            break;
                    }
                }
                response.setSpcRateVersion(StringUtils.isBlank(feeManager.getMinFeeVersion()) ? DateUtils.dateTimeNow() : feeManager.getMinFeeVersion());
            } catch (CustomizeException e) {
                logger.error(e.getCustomMessage());
                response.setCode(-1);
                response.setCodeInfo(e.getCustomMessage());
                e.printStackTrace();
            } catch (Exception e) {
                logger.error(e.getMessage());
                response.setCode(-1);
                response.setCodeInfo(e.getMessage());
                e.printStackTrace();
            }
        }
        response.setMsgId(requestBiz.getMsgId());
        response.setReceiveTime(DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_TT_HH_MM_SS));
        result.setFilename(basicRequest.getFilename().replace("REQ", "RES"));
        result.setSign(basicRequest.getSign());
        result.setBizContent(JSON.toJSONString(response));
        return result;
    }

    /**
     * 交易前预检测
     *
     * @param basicRequest
     * @param requestBiz
     * @return
     */
    public String check(BasicRequest basicRequest, FeeEnCalcRequest requestBiz) {
        String msg = "";
        if (basicRequest.getFilename().isEmpty()) {
            msg = "filename字段为null";
        } else if (basicRequest.getTimestamp().isEmpty()) {
            msg = "timestamp字段为null";
        } else if (!DateUtils.checkDate(basicRequest.getTimestamp())) {
            msg = "timestamp格式错误";
        } else if (basicRequest.getBizContent().isEmpty()) {
            msg = "bizContent字段为空";
        } else if (!DateUtils.checkDate(requestBiz.getCurPassTime())) {
            msg = "curPassTime格式错误";
        }
        return msg;
    }

    private void logVehicleEntityInfo(FeeEnCalcRequest requestBiz, String operationType) {
        logger.info("车辆[{}]到达入口,时间[{}],开始进行[{}]方式计费", requestBiz.getVehicleId(), DateUtils.convertTime(requestBiz.getCurPassTime()), operationType);
    }
}
